package com.alipay.rebate.shop.service.customer.impl;

import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.core.AbstractService;
import com.alipay.rebate.shop.dao.mapper.ActivityMapper;
import com.alipay.rebate.shop.dao.mapper.ActivityProductMapper;
import com.alipay.rebate.shop.dao.mapper.CustProductMapper;
import com.alipay.rebate.shop.dao.mapper.ProductMapper;
import com.alipay.rebate.shop.dao.mapper.ProductPageFrameworkMapper;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.model.Activity;
import com.alipay.rebate.shop.model.ActivityProduct;
import com.alipay.rebate.shop.model.CustProduct;
import com.alipay.rebate.shop.model.Product;
import com.alipay.rebate.shop.model.ProductPageFramework;
import com.alipay.rebate.shop.pojo.dingdanxia.OptimusReq;
import com.alipay.rebate.shop.pojo.haodanku.HaodankuProductListRsp;
import com.alipay.rebate.shop.pojo.pdtframework.AppPdtFrameworkAndPdtRsp;
import com.alipay.rebate.shop.pojo.pdtframework.OfficialChoice;
import com.alipay.rebate.shop.pojo.pdtframework.OwnChoice;
import com.alipay.rebate.shop.pojo.pdtframework.ProductChoice;
import com.alipay.rebate.shop.pojo.pdtframework.ProductRepoChoice;
import com.alipay.rebate.shop.pojo.pdtframework.TaobaoJingPin;
import com.alipay.rebate.shop.pojo.user.customer.SearchProductRequest;
import com.alipay.rebate.shop.pojo.user.product.ActivityProductRsp;
import com.alipay.rebate.shop.service.customer.CustomerProductService;
import com.alipay.rebate.shop.utils.DingdanxiaUtil;
import com.alipay.rebate.shop.utils.HaodankuUtil;
import com.alipay.rebate.shop.utils.ListUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CustomerProductServiceImpl extends AbstractService<Product> implements
    CustomerProductService {

  private Logger logger = LoggerFactory.getLogger(CustomerProductServiceImpl.class);
  private String HTTP_PREFIX = "http:";

  @Resource
  private ProductPageFrameworkMapper frameworkMapper;
  @Resource
  private ActivityMapper activityMapper;
  @Resource
  private ActivityProductMapper activityProductMapper;
  @Resource
  private CustProductMapper custProductMapper;
  @Resource
  private ProductMapper productMapper;

  @Override
  public PageInfo<Product> searchByCondition(SearchProductRequest request) {

    PageHelper.startPage(request.getPageNo(),request.getPageSize());
    List<Product> products = productMapper.selectGoodsByCondition(request);
    PageInfo<Product> pageInfo = new PageInfo<>(products);
    return pageInfo;

  }

  @Override
  public AppPdtFrameworkAndPdtRsp selectProductFrameworkAndProducts(Integer productPageId) {

    ProductPageFramework productPageFramework  = frameworkMapper.selectByPrimaryKey(productPageId);
    logger.debug("Is used productPageFramework is: {}", productPageFramework);
    if(productPageFramework == null ||
        StringUtils.isEmpty(productPageFramework.getDataSource())){
      throw  new BusinessException(StatusCode.PRODUCT_PAGE_FRAMEWORK_NOT_EXISTS);
    }
//    Type type = new TypeToken<Map<String, Object>>() {}.getType();
//    logger.debug("datasource is : {}",productPageFramework.getDataSource());
//    Map<String, Object> map = gson.fromJson(productPageFramework.getDataSource(),type);

//    Integer pageNo =1 , pageSize = 20;
    AppPdtFrameworkAndPdtRsp rsp = new AppPdtFrameworkAndPdtRsp();
    rsp.setFramework(productPageFramework);
//    if(map.get(ProductConstant.OWN_CHOICE_FRAMEWORK) != null){
//      logger.debug("OwnChoice product");
//      Object obj = map.get(ProductConstant.OWN_CHOICE_FRAMEWORK);
//      String json = gson.toJson(obj);
//      OwnChoice ownChoice = gson.fromJson(json, OwnChoice.class);
//      PageInfo<Product> pageInfo = selectOwnChoiceProduct(ownChoice,pageNo,pageSize);
//      rsp.setData(pageInfo);
//    }
//    if(map.get(ProductConstant.OFFICIAL_CHOICE_FRAMEWORK) != null){
//      logger.debug("OfficialChoice product");
//      Object obj = map.get(ProductConstant.OFFICIAL_CHOICE_FRAMEWORK);
//      String json = gson.toJson(obj);
//      OfficialChoice officialChoice = gson.fromJson(json, OfficialChoice.class);
//      PageInfo<Product> pageInfo = selectOfficialChoiceProduct(officialChoice,pageNo,pageSize);
//      rsp.setData(pageInfo);
//    }
//    if(map.get(ProductConstant.TAOBAO_JINPIN_FRAMEWORK) != null){
//      logger.debug("TaobaoJingPin product");
//      Object obj = map.get(ProductConstant.TAOBAO_JINPIN_FRAMEWORK);
//      String json = gson.toJson(obj);
//      TaobaoJingPin taobaoJingPin = gson.fromJson(json,TaobaoJingPin.class);
//      PageInfo<Product> pageInfo = selectTaobaoJinpinProduct(taobaoJingPin,pageNo,pageSize);
//      rsp.setData(pageInfo);
//    }
//    if(map.get(ProductConstant.PRODUCT_CHOICE_FRAMEWORK) != null){
//      logger.debug("ProductChoice product");
//      Object obj = map.get(ProductConstant.PRODUCT_CHOICE_FRAMEWORK);
//      String json = gson.toJson(obj);
//      ProductChoice productChoice = gson.fromJson(json,ProductChoice.class);
//      PageInfo<Product> pageInfo = selectProductChoiceProduct(productChoice,pageNo,pageSize);
//      rsp.setData(pageInfo);
//    }
    return rsp;
  }

  public PageInfo<Product> selectOwnChoiceProduct(
      OwnChoice ownChoice, Integer pageNo, Integer pageSize
  ){
    checkOwnChoice(ownChoice);
    logger.debug("OwnChoice is: {}",ownChoice);
    PageHelper.startPage(pageNo,pageSize);
    List<Product> products = productMapper.selectOwnChoiceProduct(ownChoice);
    PageInfo<Product> pageInfo = new PageInfo<>(products);
    return pageInfo;
  }

  public PageInfo<Product> selectOfficialChoiceProduct(
      OfficialChoice officialChoice, Integer pageNo, Integer pageSize
  ){
    checkOfficialChoice(officialChoice);
    logger.debug("OfficialChoice is: {}",officialChoice);
    PageHelper.startPage(pageNo,pageSize);
    List<Product> products ;
    if(officialChoice.getFiltrate() == null){
      products = productMapper.selectALLOfficialChoiceProduct(officialChoice);
    }else{
      products = productMapper.selectOfficialChoiceProduct(officialChoice);
    }
    PageInfo<Product> pageInfo = new PageInfo<>(products);
    return pageInfo;
  }

  public PageInfo<Product> selectTaobaoJinpinProduct(
      TaobaoJingPin taobaoJingPin, Integer pageNo, Integer pageSize
  ) throws Exception {
//    DgOptimusMaterialRequest req = new DgOptimusMaterialRequest();
//    req.setPage_no(Long.valueOf(pageNo));
//    req.setPage_size(Long.valueOf(pageSize));
//    req.setMaterial_id(taobaoJingPin.getJpkCategory());
//    TbkDgOptimusMaterialResponse rsp =  TaobaoUtil.getDgOptimusMaterial(req);
//    logger.debug("rsp is : {}",rsp);
//    List<Product> products = convertFromMapDataToProduct(rsp);
//    logger.debug("products is : {}",products);
//    return buildPageInfo(products, pageNo, ++pageNo, pageSize);
    OptimusReq req = new OptimusReq();
    req.setPage_no(pageNo);
    req.setPage_size(pageSize);
    req.setMaterial_id(taobaoJingPin.getJpkCategory());
    List<Product> products = DingdanxiaUtil.spkOptimus(req);
    logger.debug("product list is : {}",products);
    return buildPageInfo(products, pageNo, ++pageNo, pageSize);
  }

  public PageInfo<Product> selectProductChoiceProduct(
      ProductChoice productChoice, Integer pageNo, Integer pageSize
  ){
    checkProductChoice(productChoice);
    logger.debug("ProductChoice is:{}",productChoice);
    HaodankuProductListRsp rsp = HaodankuUtil.selectProductByChoice(productChoice,pageNo,pageSize);
    List<Product> products = convertFromHandankuProductToProduct(rsp);
    return buildPageInfo(products,pageNo, rsp.getMin_id(), pageSize);
  }

  @Override
  public PageInfo<Product> selectProductRepoChoiceProduct(ProductRepoChoice productRepoChoice,
      Integer productRepoId, Integer pageNo, Integer pageSize) {
    CustProduct custProduct = custProductMapper.selectByPrimaryKey(productRepoId);
    if(custProduct == null){
      throw new BusinessException(StatusCode.PRODUCT_REPO_NOTEXISTS);
    }
    logger.debug("CustProduct is: {}",custProduct);
    checkProductRepoChoice(productRepoChoice,custProduct);
    logger.debug("ProductRepoChoice is : {}",productRepoChoice);
    PageHelper.startPage(pageNo,pageSize);
    List<Product> products ;
    if(productRepoChoice.getFiltrate() == null){
      products = productMapper.selectALLProductRepoChoiceProduct(productRepoChoice);
    }else{
      products = productMapper.selectProductRepoChoiceProduct(productRepoChoice);
    }
    PageInfo<Product> pageInfo = new PageInfo<>(products);
    return pageInfo;
  }

  private PageInfo<Product> buildPageInfo(
      List<Product> products, Integer curPageNo,
      Integer nextPageNo, Integer pageSize
  ){
    logger.debug("curPageNo,nextPageNo,pageSize is : {},{},{}"
        ,curPageNo,nextPageNo,pageSize);
    PageInfo<Product> pageInfo = new PageInfo<>();
    pageInfo.setPageNum(curPageNo);
    pageInfo.setPageSize(pageSize);
    pageInfo.setList(products);
    pageInfo.setNextPage(nextPageNo);
    pageInfo.setHasNextPage(true);
    if(ListUtil.isEmptyList(products)){
      pageInfo.setHasNextPage(false);
    }
    if(nextPageNo == 0){
      pageInfo.setHasNextPage(false);
    }
    if(!pageInfo.isHasNextPage()){
      pageInfo.setNextPage(0);
    }
    logger.debug("pageInfo is : {}",pageInfo);
    return pageInfo;
  }

  /**
   * 获取所有抢免单商品信息
   * @param pageNo
   * @param pageSize
   * @return
   */
  @Override
  public ActivityProductRsp selectDailyFreeActivityProduct(Integer pageNo, Integer pageSize) {

    logger.debug("pageNo and pageSize is : {}",pageNo,pageSize);
    Activity activity = activityMapper.selectByPrimaryKey(1);
    logger.debug("Activity is : {}",activity);
    PageHelper.startPage(pageNo,pageSize);
    List<ActivityProduct> activityProducts = activityProductMapper.getProductsByActivityId(activity.getId());
    PageInfo<ActivityProduct> pageInfo = new PageInfo<>(activityProducts);
    ActivityProductRsp activityProductRsp = new ActivityProductRsp();
    activityProductRsp.setActivity(activity);
    activityProductRsp.setPageInfo(pageInfo);
    logger.debug("ActivityProductRsp is : {}",activityProductRsp);
    return activityProductRsp;
  }

  private void checkOwnChoice(OwnChoice ownChoice){
    if(ownChoice.getCategory() != null && ownChoice.getCategory().contains(0)){
      ownChoice.setCategory(null);
    }
    if(checkIfAllCategory(ownChoice.getCategory())){
      ownChoice.setCategory(null);
    }
  }

  private void checkOfficialChoice(OfficialChoice officialChoice){
    if(officialChoice.getCategory() != null && officialChoice.getCategory().contains(0)){
      officialChoice.setCategory(null);
    }
    if(checkIfAllCategory(officialChoice.getCategory())){
      officialChoice.setCategory(null);
    }
    if(officialChoice.getAdj_category() != null){
      officialChoice.setCategory(null);
      if(officialChoice.getAdj_category().equals(0)){
        officialChoice.setAdj_category(null);
      }
    }
    if(officialChoice.getFiltrate() != null && officialChoice.getFiltrate() <= 0){
      officialChoice.setFiltrate(null);
    }
    if(officialChoice.getMaxPrice() != null &&
        officialChoice.getMaxPrice().compareTo(new BigDecimal("0.00")) < 0){
      officialChoice.setMaxPrice(null);
    }
    if(officialChoice.getMinPrice() != null &&
        officialChoice.getMinPrice().compareTo(new BigDecimal("0.00")) < 0){
      officialChoice.setMinPrice(null);
    }
    if(officialChoice.getMaxBrokerage() != null && officialChoice.getMaxBrokerage() < 0){
      officialChoice.setMaxBrokerage(null);
    }
    if(officialChoice.getMinBrokerage() != null && officialChoice.getMinBrokerage() < 0){
      officialChoice.setMinBrokerage(null);
    }
  }

  private void checkProductChoice(ProductChoice productChoice){
    if(productChoice.getCategory() != null && productChoice.getCategory().contains(0)){
      productChoice.setCategory(null);
    }
    if(checkIfAllHaodankuCategory(productChoice.getCategory())){
      productChoice.setCategory(null);
    }
    if(productChoice.getMaxTicket() != null &&
        productChoice.getMaxTicket().compareTo(new BigDecimal("0.00")) <0){
      productChoice.setMaxTicket(null);
    }
    if(productChoice.getMinTicket() != null &&
        productChoice.getMinTicket().compareTo(new BigDecimal("0.00")) <0){
      productChoice.setMinTicket(null);
    }
    if(productChoice.getMinAfterPrice() != null &&
        productChoice.getMinAfterPrice().compareTo(new BigDecimal("0.00")) <0){
      productChoice.setMinAfterPrice(null);
    }
    if(productChoice.getMaxAfterPrice() != null &&
        productChoice.getMaxAfterPrice().compareTo(new BigDecimal("0.00")) <0){
      productChoice.setMaxAfterPrice(null);
    }
  }

  private void checkProductRepoChoice(ProductRepoChoice productRepoChoice,CustProduct custProduct){
    Double minPrice = productRepoChoice.getMinPrice();
    Double maxPrice = productRepoChoice.getMaxPrice();
    Double cusMinPrice = custProduct.getPriceBegin();
    Double cusMaxPrice = custProduct.getPriceEnd();
    // 如果用户没有进行筛选，则已数据库的为准
    if(minPrice == null){
      productRepoChoice.setMinPrice(cusMinPrice);
    }
    if(maxPrice == null){
      productRepoChoice.setMaxPrice(cusMaxPrice);
    }
    // 价格搜索是否超出了范围
    if(minPrice != null && cusMinPrice != null && minPrice<cusMinPrice){
      productRepoChoice.setMinPrice(cusMinPrice);
    }
    if(maxPrice != null && cusMaxPrice!= null && maxPrice>cusMaxPrice){
      productRepoChoice.setMaxPrice(cusMaxPrice);
    }
    productRepoChoice.setFiltrate(custProduct.getProductFrom());
    productRepoChoice.setMinBrokerage(custProduct.getCommissionBegin());
    productRepoChoice.setMaxBrokerage(custProduct.getCommissionEnd());
    if(productRepoChoice.getTmall()!=null && productRepoChoice.getTmall()==0){
      productRepoChoice.setTmall(null);
    }
    if(StringUtils.isEmpty(productRepoChoice.getKeyword())){
      productRepoChoice.setKeyword(custProduct.getKeyWord());
    }
    if(!StringUtils.isEmpty(custProduct.getClassify())){
      String[] cidArray = custProduct.getClassify().split(",");
      List<Integer> cids = convertStringArrToListInteger(cidArray);
      productRepoChoice.setCategory(cids);
      if(checkIfAllCategory(productRepoChoice.getCategory())){
        productRepoChoice.setCategory(null);
      }
    }
    productRepoChoice.setSell(custProduct.getMonthSale());
    if(productRepoChoice.getCategory() != null && productRepoChoice.getCategory().contains(0)){
      productRepoChoice.setCategory(null);
    }
    if(productRepoChoice.getFiltrate() != null && productRepoChoice.getFiltrate() <= 0){
      productRepoChoice.setFiltrate(null);
    }
    if(productRepoChoice.getMaxPrice() != null && productRepoChoice.getMaxPrice() < 0){
      productRepoChoice.setMaxPrice(null);
    }
    if(productRepoChoice.getMinPrice() != null && productRepoChoice.getMinPrice() < 0){
      productRepoChoice.setMinPrice(null);
    }
    if(productRepoChoice.getMinBrokerage() != null && productRepoChoice.getMinBrokerage() < 0){
      productRepoChoice.setMinBrokerage(null);
    }
    if(productRepoChoice.getMaxBrokerage() != null && productRepoChoice.getMaxBrokerage() < 0){
      productRepoChoice.setMaxBrokerage(null);
    }
  }

  private List<Product> convertFromHandankuProductToProduct(HaodankuProductListRsp rsp) {
    List<Product> products = new ArrayList<>();
    if (rsp == null || rsp.getData() == null) {
      return products;
    }
    rsp.getData().forEach(haodankuProduct -> {
      Product product = HaodankuUtil.convert2Product(haodankuProduct);
      products.add(product);
    });
    return products;
  }

  private boolean checkIfAllCategory(List<Integer> list){
    if(ListUtil.isEmptyList(list)){
      return true;
    }
    return list.contains(1) && list.contains(2) && list.contains(3)
        && list.contains(4) && list.contains(5) && list.contains(6)
        && list.contains(7) && list.contains(8) && list.contains(9)
        && list.contains(10) && list.contains(11) && list.contains(12)
        && list.contains(13) && list.contains(14);
  }

  private boolean checkIfAllHaodankuCategory(List<Integer> list){
    if(ListUtil.isEmptyList(list)){
      return true;
    }
    return list.contains(1) && list.contains(2) && list.contains(3)
        && list.contains(4) && list.contains(5) && list.contains(6)
        && list.contains(7) && list.contains(8) && list.contains(9)
        && list.contains(10) && list.contains(11) && list.contains(12)
        && list.contains(13);
  }


  private List<Integer> convertStringArrToListInteger(String arr[]){
    List<Integer> list = new ArrayList<>();
    if(arr == null || arr.length ==0){
      return null;
    }
    for(String value : arr){
      list.add(Integer.valueOf(value));
    }
    return list;
  }
}
